package warehouse;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class AccountBean {
	String username;
	int privilege = -1;
	int staffNo;
	
	
	
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public int getPrivilege() {
		return privilege;
	}
	public void setPrivilege(int privilege) {
		this.privilege = privilege;
	}
	public int getStaffNo() {
		return staffNo;
	}
	public void setStaffNo(int staffNo) {
		this.staffNo = staffNo;
	}
	/**
	 * 登录
	 * @param username 用户名
	 * @param password 密码
	 * @return 是否登录成功
	 */
	public boolean login(String username,String password){
		Connection connection = DatabaseBean.connect();
		
		String sql = String.format("SELECT * FROM account WHERE username='%s' AND password='%s'", 
				username,password);
		Statement stmt=null;
		try {
			stmt=connection.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			if(!rs.next()) {
				//如果没有找到匹配的账号
				return false;
			}
			else {
				//登录成功，将所有数据写入属性
				this.username = username;
				this.privilege = rs.getInt("privilege");
				this.staffNo = rs.getInt("staffNo");
				return true;
			}
			
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		}
		finally {
			try {
				connection.close();
			} catch (SQLException e) {
				e.printStackTrace();
				return false;
			}
		}
	}	
	public static void main(String args[]) {
		//单元测试代码
		AccountBean account = new AccountBean();
		
		boolean  res = account.login("root", "1234");
		System.out.println(res);
		res = account.login("root", "134");
		System.out.println(res);
		res = account.login("roo", "1234");
		System.out.println(res);
		
		account.login("U1", "5678");
		int privilege=account.getPrivilege();
		String username = account.getUsername();
		int staffNo = account.getStaffNo();
		System.out.println(username+staffNo+privilege);
		
	}
	
}
